import axios from 'axios'
import { useToken } from '@/stores'
import { message } from 'ant-design-vue'
import router from '@/router'

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  axios.defaults.timeout = 60 * 1000
  axios.defaults.withCredentials = true

  axios.defaults.baseURL =
    import.meta.env.NODE_ENV === 'development' ? '/api' : '//api-hmzs.itheima.net/api/'

  const HttpCode = {
    SUCCESS: 10000, // 成功
    NOT_AUTH: 40001 // 认证失败
  }

  // 请求拦截器
  axios.interceptors.request.use(
    (config) => {
      const { getToken } = useToken()
      const token = getToken()
      const defaultHeader = {}

      if (token) {
        defaultHeader['Authorization'] = token
      }
      config.headers = {
        ...defaultHeader,
        ...config.headers
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  axios.interceptors.response.use(
    (res) => {
      const { data, status } = res
      if (status === 200) {
        const { code, data: resData, msg } = data
        if (code === HttpCode.NOT_AUTH) {
          return router.push('/login')
        }
        if (code !== HttpCode.SUCCESS) {
          message.error(data?.msg || '接口请求失败')
          return Promise.reject(msg)
        }
        return resData
      }
    },
    (error) => {
      const { response } = error
      const { removeToken } = useToken()

      // 如果不是在乾坤场景下
      if (response.status === 401) {
        message.error('授权失败，请重新登录！')
        removeToken()
        // router.push({ path: '/login', query: { redirect: router.currentRoute.value.path } })
      } else {
        const data = error?.response?.data
        message.error(data?.msg || '接口请求失败')
        return Promise.reject(data?.msg || '接口请求失败')
      }
    }
  )
}

export const request = (config) =>
  axios(config)
    .then((response) => response)
    .catch((error) => Promise.reject(error))

export const Get = (url, params, config) =>
  request(
    Object.assign({}, config, {
      url,
      params: { ...params },
      method: 'get'
    })
  )

export const Post = (url, data, config) =>
  request(
    Object.assign({}, config, {
      url,
      data,
      method: 'post'
    })
  )

export const Put = (url, data, config) =>
  request(
    Object.assign({}, config, {
      url,
      data,
      method: 'put'
    })
  )

export const Delete = (url, data, config) =>
  request(
    Object.assign({}, config, {
      url,
      data,
      method: 'delete'
    })
  )
